/*
 * @name: **列表
 * @content:
 * @Author: joyce
 * @Date: 2020-05-29 15:38:26
 */
const express = require("express");
const router = express.Router();
var multer = require("multer");
const fs = require("fs");
const path = require("path");
const vote = require("../model/vote");
const voteDetail = require("../model/voteDetail");
const recommend = require("../model/recommend");

// 这里dest对应的值是你要将上传的文件存的文件夹
// var upload = multer({dest:'./public/images'});
// 使用硬盘存储模式设置存放接收到的文件的路径以及文件名
var storage = multer.diskStorage({
  destination: function(req, file, cb) {
    // 接收到文件后输出的保存路径（若不存在则需要创建）
    cb(null, path.join(__dirname, "../public/images/voteimg/"));
  },
  filename: function(req, file, cb) {
    // 将保存文件名设置为 时间戳 + 文件原始名，比如 151342376785-123.jpg
    let extname = file.mimetype.split("/")[1];
    let imgname =
      Date.now() +
      parseInt(Math.random() * 999) +
      parseInt(Math.random() * 2222);
    let keepname = imgname + "." + extname;

    cb(null, keepname);
  }
});

// 创建 multer 对象
var upload = multer({
  storage: storage
});

router.post(
  "/api/v1/uploadImagevote",
  upload.fields([
    {
      name: "images"
    },
    {
      name: "optionimages"
    }
  ]),
  function(req, res) {
    console.log(req.body);
    let filesData = req.files;
    let formData = JSON.parse(req.body.formData);
    console.log(!!filesData.images);
    console.log(!!filesData.optionimages);
    if (filesData.images) {
      formData.images = filesData.images[0].filename;
    }

    if (filesData.optionimages) {
      filesData.optionimages.forEach((el, index) => {
        formData.option[index].optionfile = el.filename;
      });
    }
    console.log(formData);
    const info = new vote(formData);
    info.save(function(err) {
      if (err) {
        console.log(err);
        res.status(500).send(err);
      } // 已保存
      res.json({
        code: 200,
        data: "succse"
      });
    });
  }
);

router.post("/api/v1/put_voteImageTests", function(req, res) {
  console.log("req");
  console.log(req.body);
  vote.remove(
    {
      _id: req.body._id
    },
    async function(err, doc) {
      if (err) {
        res.json({
          code: 400,
          message: "err"
        });
      } else {
        //删除主图图片
        if (req.body.images) {
          var filepath =
            path.join(__dirname, "../public/images/voteimg/") + req.body.images;
          fs.unlink(filepath, function(err) {
            console.log(err);
            console.log("err==");
          });
        }
        //删除选项图片
        if (req.body.option[0].optionfile) {
          req.body.option.forEach(e => {
            var filepath =
              path.join(__dirname, "../public/images/voteimg/") + e.optionfile;
            fs.unlink(filepath, function(err) {
              console.log(err);
              console.log("err==");
            });
          });
        }

        await voteDetail.deleteMany({
          voteId: req.body._id
        });
        //删除推荐
        await recommend.deleteOne({
          voteid: req.body._id
        });
        res.json({
          code: 200,
          mess: "succse"
        });
      }
    }
  );
});

module.exports = router;
